package service

import (
	"fmt"
	"github.com/tebeka/selenium"
	"math/rand"
	"mcncomment/src/util"
	"os"
	"strconv"
	"time"
)

func Comment() {

	err := error(nil)

	//获取基础配置参数
	configFields := util.ListConfigFields()

	//获取评论集合
	comments = util.ListComments()

	//加载基础配置（浏览器驱动、房间号、评论发送周期）
	chromeDriverPath = configFields[0]
	port, err = strconv.Atoi(configFields[1])
	if err != nil {
		panic(err)
	}
	liveRoomUrl = configFields[2]
	cycle, err = strconv.Atoi(configFields[3])
	if err != nil {
		panic(err)
	}

	//读取cookies
	cookies := util.ListCookies()

	// Start a WebDriver server instance
	opts := []selenium.ServiceOption{
		selenium.Output(os.Stderr), // Output debug information to STDERR.
	}
	selenium.SetDebug(false)
	service, _ := selenium.NewChromeDriverService(chromeDriverPath, port, opts...)
	defer service.Stop()

	// Connect to the WebDriver instance running locally.
	caps := selenium.Capabilities{"browserName": "chrome"}
	wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
	if err != nil {
		panic(err)
	}

	//访问抖音官网
	err = wd.Get("https://www.douyin.com/")
	if err != nil {
		panic(err)
	}

	//添加token
	for _, c := range cookies {
		err := wd.AddCookie(&c)
		if err != nil {
			panic(err)
		}
	}

	//打开直播间页面
	err = wd.Get(liveRoomUrl)
	if err != nil {
		panic(err)
	}

	//延迟3秒，避免页面加载不全
	time.Sleep(time.Duration(3) * time.Second)

	//开始自动评论
	for {
		//获取输入框
		we, err := wd.FindElement(selenium.ByCSSSelector, ".webcast-chatroom___textarea")
		if err != nil {
			panic(err)
		}
		we.Clear()

		// 随机输入评论
		err = we.SendKeys(comments[rand.Intn(len(comments))])
		if err != nil {
			panic(err)
		}

		//获取按钮
		we, err = wd.FindElement(selenium.ByCSSSelector, ".webcast-chatroom___send-btn")
		if err != nil {
			panic(err)
		}

		//休眠一段时间后点击按钮
		time.Sleep(time.Duration(cycle) * time.Second)
		err = we.Click()
		if err != nil {
			panic(err)
		}
	}

	defer wd.Quit()
}
